Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

var record_start = 0; 

var sm = new Ext.grid.CheckboxSelectionModel();
var cm=new Ext.grid.ColumnModel([ 
sm,
new Ext.grid.RowNumberer({header: "编号",
width:40, 
renderer:function(value,metadata,record,rowIndex){ 
return record_start + 1 + rowIndex; 
} 
}),
{header:'客户ID',dataIndex:'custId',hidden:true},
{header:'客户名称',dataIndex:'custName',width:100},
{header:'所属行业',dataIndex:'industryType',width:100}, 
{header:'信用评级',dataIndex:'creditLevel',width:100},
{header:'信贷余额(元)',dataIndex:'balance',width:100},
{header:'风险暴露分类',dataIndex:'exposureType',width:100},
{header:'违约状态',dataIndex:'defaultStat',width:100},
{header:'经办人',dataIndex:'inputUserName',width:100},
{header:'经办机构',dataIndex:'inputOrgName',width:100},
]); 
var ds=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'customer/listCustomer.do',
method:'POST'
}), 
reader:new Ext.data.JsonReader({ 
totalProperty:'total',  
root:'customer'},[
{name:'custId'}, 
{name:'custName'},  
{name:'industryType'},
{name:'creditLevel'},
{name:'balance'},
{name:'exposureType'},
{name:'defaultStat'},
{name:'inputUserName'},
{name:'inputOrgName'},
]) 
}); 

var eventsTypeStore=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'showType.do?type=EventType',
method:'GET'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'name'}, 
{name:'code'}
]) ,
autoLoad:true
}); 

var conditionStore = new Ext.data.SimpleStore({
	   fields : ['id', 'text'],
	   data : [['custId', '客户编号'], ['custName', '客户名称']]
});

var grid=new Ext.grid.GridPanel({ 
id:'myCustomers',
renderTo:"customer_list", 
stripeRows:true,//斑马线效果
title:"我的客户列表", 
height:500, 
cm:cm,
store: ds, 
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },   
            bbar: new Ext.PagingToolbar({   
                pageSize: 20,   
                store: ds,
                displayInfo: true,   
                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
                emptyMsg: "没有数据" ,
                doLoad : function(start){ 
   record_start = start; 
var o = {}, pn = this.getParams(); 
          o[pn.start] = start; 
          o[pn.limit] = this.pageSize; 
this.store.load({params:o}); 
     }   
            }),
 tbar: [
 {text:'查看该客户的所有债项',handler:listDebt},   
 '->',
 {xtype:'combo',
 id:'condition',
 name: 'condition', 
 store: conditionStore,
 fieldLabel: '请选择查询条件',
 valueField : 'id',
 displayField : 'text',
 emptyText : '请选择查询条件',
 triggerAction : 'all',
 editable: false,
 mode:'local',
 width:110
 },'',
 {xtype:'textfield',id:'keyword',width:180},
 {text:'查询',handler:findCustomer},
 '-',
 {text:'清空',handler: callBack} ]   
});
ds.load({params:{start:0,limit:20}}); 



function findCustomer(){

var condition = Ext.getCmp('condition').getValue();
var keyword = Ext.getCmp('keyword').getValue();

if(condition == '' || condition == null){
Ext.Msg.alert('提示', '请选择查询条件！'); 
}
else{

ds.baseParams={condition:condition, keyword: keyword};
ds.proxy = new Ext.data.HttpProxy({
				url:'customer/findCustomer.do',
				method:'POST'
			}); 
ds.reader = new Ext.data.JsonReader({ 
					totalProperty:'total',  
					root:'resultData'},[
										{name:'custId', mapping: 'custId'}, 
										{name:'custName', mapping: 'custName'},  
										{name:'industryType', mapping: 'industryType'},
										{name:'defaultStat', mapping: 'defaultStat'},
										{name:'exposureType', mapping: 'exposureType'},
										{name:'creditLevel',mapping:'creditLevel'},
										{name:'balance',mapping:'balance'},
										{name:'inputUserName', mapping:'inputUserName'},
										{name:'inputOrgName', mapping:'inputOrgName'},
				]);
				   
ds.load({params:{start:0,limit:20}});
record_start = 0;  	
}
}

function callBack(){

Ext.getCmp('condition').clearValue();
Ext.getCmp('keyword').setValue('');
ds.proxy = new Ext.data.HttpProxy({
				url:'customer/listCustomer.do',
				method:'POST'
			}); 
ds.reader = new Ext.data.JsonReader({ 
					totalProperty:'total',  
					root:'customer'},[
										{name:'custId', mapping: 'custId'}, 
										{name:'custName', mapping: 'custName'},  
										{name:'industryType', mapping: 'industryType'},
										{name:'defaultStat', mapping: 'defaultStat'},
										{name:'exposureType', mapping: 'exposureType'},
										{name:'creditLevel',mapping:'creditLevel'},
										{name:'balance',mapping:'balance'},
										{name:'inputUserName', mapping:'inputUserName'},
										{name:'inputOrgName', mapping:'inputOrgName'},
				]);   
ds.load({params:{start:0,limit:20}});
record_start = 0;

}

var cm2=new Ext.grid.ColumnModel([ 
sm,
new Ext.grid.RowNumberer({header: "编号",width:40}),
{header:'违约事件流水号',dataIndex:'serialNo',hidden:true},
{header:'违约事件类型',dataIndex:'eventType',width:100},
{header:'登记时间',dataIndex:'inputDate',width:100},
{header:'当前状态',dataIndex:'status',width:100}
]); 

var ds2=new Ext.data.Store({  
reader:new Ext.data.JsonReader({},[
{name:'serialNo'}, 
{name:'eventType'}, 
{name:'inputDate'},  
{name:'status'}
]) 
}); 

var panel=new Ext.Panel({
	title:"当前客户",
	height:60,
	html:"<table width=\"100%\">\r\n <tr>\r\n " +
         "<td width=\"40%\" style=\"text-align:left;\">客户ID：\$\{currentCustId\}</td>\r\n " +
         "<td width=\"60%\" style=\"text-align:left;\">客户名称：${currentCustName}</td>\r\n" +
         "</tr></table>\r\n"
}); 

var grid2=new Ext.grid.GridPanel({ 
id:'defaultList', 
stripeRows:true,
title:"当前客户违约事件列表", 
height:370, 
cm:cm2,
store: ds2, 
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },   
            bbar: new Ext.PagingToolbar({   
                pageSize: 10,   
                store: ds2,   
                displayInfo: true,   
                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
                emptyMsg: "没有数据"   
            }),
 tbar: [
 {text:'新增',id:'btnAdd'},
  '-',
 {text:'查看详情',handler:checkDetail},
 '-',
 {text:'删除',handler:del},
 '-',
 {text:'提交',handler:commit}
 ]              
});

var win2 = new Ext.Window({ 
id: 'win2', 
title: '<div align="center">违约事件登记</div>', 
width: 800, 
height: 500, 
modal: true, 
resizable: false, 
closeAction: 'hide', 
plain: true,  
items:[panel,grid2 ]
});

//新增客户表单
addForm = new Ext.form.FormPanel({ 
id: 'addForm', 
width: 560, 
height: 280, 
//样式 
bodyStyle: 'margin:3px 3px 3px 3px', 
frame: true, 
xtype: 'filedset', 
labelWidth: 80, 
items: 
[ { xtype: 'fieldset', 
title: '客户违约事件信息', 
collapsible: true, 
autoHeight: true, 
autoWidth: true, 
items: 
[{layout:"column",
items:[{
	columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
xtype: 'textfield',
id: 'custId', 
name: 'custId', 
fieldLabel: '客户ID',
editable: false,  
width: 150 
}]},{ columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
xtype: 'textfield',
id: 'custName', 
name: 'custName', 
fieldLabel: '客户名称',
editable: false, 
width: 150 
}]} 
]},{ layout : "form",
           items : [{
xtype: 'textfield',
id: 'rating', 
name: 'rating', 
fieldLabel: '违约前评级',  
allowBlank: true,  
width: 150  
}]},
{layout:"column",
items:[{
	columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
xtype: 'combo', 
 id : "eventType",
              store :eventsTypeStore,
              fieldLabel: '事件类型',
              valueField : 'code',
              displayField : 'name',
              emptyText : '请选择事件类型...',
              allowBlank : false,
              blankText:'请选择事件类型',
              typeAhead : true,
              width: 150,
              mode:'remote',  
              hiddenName:'eventType',
              editable: false,
              triggerAction : 'all',
              selectOnFocus : true 
}]},{ columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
xtype: 'datefield',
id: 'eventDate', 
name: 'eventDate', 
fieldLabel: '违约发生日期',  
allowBlank: true, 
editable:false, 
width:150 ,
format : 'Y-m-d'
}]} 
]},
{ layout : "form",
           items : [{
xtype: 'textarea',
id: 'eventDesc', 
name: 'eventDesc', 
fieldLabel: '事件描述', 
emptyText: '必填', 
blankText: '事件描述不能为空', 
allowBlank: false,  
maxLength:200,
maxLengthText:'最多只允许输入200个汉字',
height:100,
anchor: '97%' 
}]},
{xtype:'hidden',
id:'serialNo',
name:'serialNo',
allowBlank: true
}
] 
}]
});

//新增窗口 
addWin = new Ext.Window({ 
id: 'addWin', 
title: '新增客户违约事件', 
width: 580, 
height: 320, 
//背景遮罩 
modal: true, 
//重置大小 
resizable: false, 
//当关闭按钮被点击时执行的动作 
closeAction: 'hide', 
plain: true, 
buttonAlign: 'right', 
items:addForm, 
buttons: 
[  
{ text: '提交', id: 'btnSubmit' } ,
{ text: '重置', handler: function(){ Ext.getCmp('addForm').form.reset();}},
{ text: '关闭', handler: function() { Ext.getCmp('addWin').hide(); } }

] 
});

function addRoleFunction() {
	
		if(addForm.form.isValid()){
		addForm.form.doAction('submit', { 
			url : 'obligation/addCustDefaultEvent.do', 
			method : 'post', 
			success : function() { 
			Ext.getCmp("addWin").hide();
			grid2.store.reload();
			Ext.Msg.alert('提示', '添加成功！'); 
			}, 
			failure : function() { 
			Ext.Msg.alert('提示', '添加失败！'); 
			} 
		});  
	}
 }

//添加按钮单击事件 
function btnAddClick() { 
Ext.getCmp('addForm').form.reset();

Ext.Ajax.request({
  url:'obligation/getCustomer.do',
  method:'GET',
  success:function(response){
	var json = Ext.util.JSON.decode(response.responseText);
	Ext.getCmp('custId').setValue(json.custId);
	Ext.getCmp('custName').setValue(json.custName);
  },failure:function(){
    Ext.MessageBox.alert("客户信息引入失败！");
  }
});  
Ext.getCmp("addWin").buttons[0].handler = addRoleFunction; 
Ext.getCmp("addWin").show(); 
}; 

//新增按钮 
var addUserBtn = Ext.getCmp('btnAdd'); 
addUserBtn.on('click', btnAddClick); 

//删除客户
function del(){
if (grid2.getSelectionModel().getSelections()[0] == undefined) { 
	Ext.Msg.alert("提示", "请选中要删除的内容"); 
} 
else{
	 var status =  grid2.getSelectionModel().getSelections()[0].data.status;     
	if(status == '待认定状态' ){
		Ext.Msg.alert("提示", "当前违约事件已提交，不能删除！");
	}
	else if(status == '已认定' ){
		Ext.Msg.alert("提示", "当前违约事件已认定，不能删除！");
	}
	else {Ext.MessageBox.confirm('提示', '确实要删除所选的内容吗？', deleteConfirm);}
}
}

function deleteConfirm(btn){
if (btn == 'yes') {
 Ext.Ajax.request({
  url:'obligation/deleteCustDefaultEvent.do',
  params : {serialNo : grid2.getSelectionModel().getSelections()[0].data.serialNo},
  method:'POST',
  success:function(){
   Ext.MessageBox.alert("提示","删除成功！");
   grid2.store.reload(); 
  },failure:function(){
    Ext.MessageBox.alert("提示", "删除失败！"); 
  }
});
}
}

function checkDetail(){
if (grid2.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要查看的内容！"); 
}
else{
	var selectedId = grid2.getSelectionModel().getSelections()[0].data.serialNo;
    var status =  grid2.getSelectionModel().getSelections()[0].data.status;     
   	addForm.form.reset(); 
	
   	if(status == '待认定状态' ){
		addWin.buttons[0].handler = function(){Ext.Msg.alert("提示", "当前违约事件已提交，不能修改！");};
	}
	else if(status == '已认定' ){
		addWin.buttons[0].handler = function(){Ext.Msg.alert("提示", "当前违约事件已认定，不能修改！");};
	}
   	else{addWin.buttons[0].handler = edit;}
	 

	Ext.Ajax.request({
		url:'obligation/getCustDefaultEvent.do',
		params : { serialNo: selectedId},
		method:'POST',
  		success:function(response){
		 	var json = Ext.util.JSON.decode(response.responseText);
		 	Ext.getCmp('serialNo').setValue(json.serialNo);
		 	Ext.getCmp("custId").setValue(json.custId);
		  	Ext.getCmp("eventType").setValue(json.eventType);
			Ext.getCmp("eventDesc").setValue(json.eventDesc);
		  	Ext.getCmp("eventDate").setValue(json.eventDate);
			Ext.getCmp("addWin").show(); 
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
}); 
}
}

function edit(){
	if(addForm.form.isValid()){
	 addForm.form.doAction('submit', { 
        url : 'obligation/editCustDefaultEvent.do', 
        method : 'post', 
		success : function() {
		   Ext.getCmp('addWin').hide();
			grid2.store.reload();
			Ext.Msg.alert('提示', '编辑成功！'); 
		}, 
        failure : function() { 
			Ext.Msg.alert('提示', '编辑失败！'); 
 		} 
	}); 
}
}

grid2.addListener('rowdblclick',checkDetail);

function commit(){
	if (grid2.getSelectionModel().getSelections()[0] == undefined) { 
		Ext.Msg.alert("提示", "请选中要操作的内容！"); 
	}
	else{
		var selectedId = grid2.getSelectionModel().getSelections()[0].data.serialNo;
		var status =  grid2.getSelectionModel().getSelections()[0].data.status;
		if(status == '待认定状态' ){
		Ext.Msg.alert("提示", "当前违约事件已提交，不能重复提交！");
	}
	else if(status == '已认定' ){
		Ext.Msg.alert("提示", "当前违约事件已认定！");
	}else{
		Ext.MessageBox.confirm('提示', '确定提交此违约事件吗？', 
			confirm = function(){
			Ext.Ajax.request({
			url:'obligation/commitCustDefaultEvent.do',
			params : { serialNo: selectedId},
			method:'POST',
	  		success:function(response){
			 	 grid2.store.reload();
		  },failure:function(){
		    	Ext.MessageBox.alert("请求异常！");
  			}
			}); 
		});}
}
}

function listDefault(){
	if (grid.getSelectionModel().getSelections()[0] == undefined) { 
		Ext.Msg.alert("提示", "请选中要操作的内容！"); 
}
else{
	var selectedCustId = grid.getSelectionModel().getSelections()[0].data.custId;
	
	ds2.proxy = new Ext.data.HttpProxy({
		url:'obligation/listCustomerDefaultEvent.do?custId='+selectedCustId,
		method:'POST'
	});
	ds2.load();
	
	Ext.getCmp('win2').show();
}
}

function listDebt(){
	if (grid.getSelectionModel().getSelections()[0] == undefined) { 
		Ext.Msg.alert("提示", "请选中要操作的内容！"); 
	}
	else{
		var selectedCustId = grid.getSelectionModel().getSelections()[0].data.custId;
		    Ext.Ajax.request({
			  url:'checkRequest.do',
			  method:'GET',
			  success:function(){
			  window.location.href="obligation/showDebtList.do?CustId="+selectedCustId;
			  },failure:function(){
			    Ext.MessageBox.alert("请求异常！");
			  }
			});  
	}
}

function rowdblclickFn(grid, rowIndex, e){//双击事件  
             var row = grid.getStore().getAt(rowIndex); 
             var selectedCustId = row.get("custId");
             Ext.Ajax.request({
  url:'checkRequest.do',
  method:'GET',
  success:function(){
  window.location.href="obligation/showDebtList.do?CustId="+selectedCustId;
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
});  
}   
grid.addListener('rowdblclick',rowdblclickFn);
}); 